package org.dandelion.papercheck.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;


import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Map;

public class JWTUtils {
    private static final String SIGN = "OASystemToken!";

    //生成jwt令牌
    public static String getToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();
        map.forEach(builder::withClaim);
        Calendar instance = Calendar.getInstance();
        // 2个小时的令牌
        instance.add(Calendar.SECOND, 60 * 60 * 2);
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(SIGN));
    }

    //校验JWT令牌
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    //获取Token中的payload
    public static DecodedJWT getToken(String token) {
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    public static String getAdminFromToken(String token) {
        return JWTUtils.getToken(token).getClaim("admin").asString();
    }

    public static Long getIdFromRequest(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("token");

        // 从 http 请求头中取出 token
        String id_str = JWTUtils.getToken(token).getClaim("id").asString();
        return Long.valueOf(id_str);
    }

    public static String getNameFromRequest(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("token");
        // 从 http 请求头中取出 token
        return JWTUtils.getToken(token).getClaim("name").asString();

    }

    public static String getVIP(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("token");
        // 从 http 请求头中取出 token
        return JWTUtils.getToken(token).getClaim("vip").asString();
    }

    public static String getAdmin(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("token");
        // 从 http 请求头中取出 token
        return JWTUtils.getToken(token).getClaim("admin").asString();
    }
}
